import sys

if sys.version_info[0] >= 3:
    import PySimpleGUI as sg
else:
    import PySimpleGUI27 as sg
import time

sg.ChangeLookAndFeel('Black')
sg.SetOptions(element_padding=(0, 0))
layout = [
    [
        sg.Text('时:分:秒', size=(20, 2), font=('Helvetica', 14))
    ],
    [
        sg.Text('祝您顺利', size=(16, 2), font=('Helvetica', 20), justification='center', key='text_time')
    ],
    [
        sg.Button('开始计时', button_color=('white', '#001480')),
        sg.Button('重新计时', button_color=('white', '#007339')),
        sg.Button('中止发送', button_color=('white', 'firebrick4'))
    ]
]

win3 = sg.Window('邮件发送倒计时', layout, no_titlebar=False, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True)

set_end = 1  # 单位分钟 int

paused = False  # 执行标志
start_time = 0  # 记录一次执行开始的时间，s
running_time = 0  # 记录一次执行时间 s
left_time = set_end * 60  # 记录剩余时间 s
show_time = left_time  # 最终用于展示的时间 s

while True:
    if paused:
        ev3, vals3 = win3.read(1000)
        now_time = int(time.time())  # 当前时间，s
        running_time = now_time - start_time  # 执行时间，s
        show_time = left_time - running_time  # 剩余时间
    else:
        ev3, vals3 = win3.read(1000)

    button_name = win3["开始计时"].get_text()
    if ev3 == '重新计时':
        print("重新计时")
        # 变量统统复位
        running_time = 0
        left_time = set_end * 60
        show_time = left_time
        paused = False
    if ev3 == '开始计时' and button_name == '暂停计时':  # 暂停
        print("暂停计时")
        paused = False
        start_time = int(time.time())
        win3[ev3].update(text='开始计时')
    if ev3 == '开始计时' and button_name == '开始计时':
        print("开始计时")
        start_time = int(time.time())  # 开始时间，s
        left_time = left_time - running_time
        paused = True
        win3[ev3].update(text='暂停计时')
    if ev3 is None or ev3 == '中止发送':  # 中止发送
        paused = False
        break
    if show_time <= 0 and button_name == '暂停计时':
        paused = False
        print("倒计时结束")
        win3["开始计时"].update(text='开始计时')

    # --------- Display timer in win3 --------
    win3['text_time'].update('{:02d}:{:02d}:{:02d}'.format(show_time // 3600, (show_time // 60) % 60, show_time % 60))
